<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="packageName">
        <el-input
          v-model="queryParams.packageName"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['hxq_package:hxq_package:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hxq_package:hxq_package:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hxq_package:hxq_package:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['hxq_package:hxq_package:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="hxq_packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="套餐唯一标识符" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="packageName" />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="进价" align="center" prop="basePrice" />
      <el-table-column label="销售价格" align="center" prop="salePrice" />
      <el-table-column label="利润" align="center" prop="profitPrice" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="积分" align="center" prop="requiredPoints" />

<!--      <el-table-column label="时效" align="center" prop="timeLimit.number+timeLimit.unit" />-->
      <el-table-column label="时效" align="center">
        <template #default="scope">
          {{ scope.row.timeLimit.number }}{{ scope.row.timeLimit.unit }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['hxq_package:hxq_package:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['hxq_package:hxq_package:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改套餐管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="hxq_packageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="进价" prop="basePrice">
          <el-input v-model="form.basePrice" placeholder="请输入进价" />
        </el-form-item>
        <el-form-item label="销售价格" prop="salePrice">
          <el-input v-model="form.salePrice" placeholder="请输入销售价格" />
        </el-form-item>
        <el-form-item label="利润" prop="profitPrice">
          <el-input v-model="form.profitPrice" placeholder="请输入利润" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in sys_show_hide"
                :key="dict.value"
                :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="积分" prop="requiredPoints">
          <el-input v-model="form.requiredPoints" placeholder="请输入使用此套餐所需的积分" />
        </el-form-item>
        <el-form-item label="时效" prop="timeLimit">
          <el-input v-model="form.timeLimit.number" placeholder="请输入时效数值" style="width: 45%;" />
          <el-select v-model="form.timeLimit.unit" placeholder="请选择时效单位" style="width: 45%; margin-left: 5px;">
            <el-option label="年" value="年"></el-option>
            <el-option label="月" value="月"></el-option>
            <el-option label="日" value="日"></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">本套餐都包含什么产品呢？</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddPackageProduct">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeletePackageProduct">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="packageProductList" :row-class-name="rowPackageProductIndex" @selection-change="handlePackageProductSelectionChange" ref="packageProduct">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="产品" prop="productId" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.productId" filterable placeholder="请选择产品ID, 关联product表">
                <el-option
                  v-for="product in products"
                  :key="product.id"
                  :label="product.name"
                  :value="product.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="次数" prop="quantity" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入该产品在套餐中的数量" />

            </template>
          </el-table-column>

        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Hxq_package">
import { listHxq_package, getHxq_package, delHxq_package, addHxq_package, updateHxq_package } from "@/api/hxq_package/hxq_package";
import {listProduct} from "@/api/product/product"
const { proxy } = getCurrentInstance();
const { sys_show_hide } = proxy.useDict('sys_show_hide');


const hxq_packageList = ref([]);
const packageProductList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedPackageProduct = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const products = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    packageName: null,
    status: null,
  },
  rules: {
    timeLimit: [
      { required: true, message: "时效不能为空", trigger: "blur" },
      { validator: validateTimeLimit, trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询套餐管理列表 */
function getList() {
  loading.value = true;
  listHxq_package(queryParams.value).then(response => {
    hxq_packageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    packageName: null,
    description: null,
    basePrice: null,
    salePrice: null,
    profitPrice: null,
    status: null,
    requiredPoints: null,
    creatorId: null,
    modifierId: null,
    createTime: null,
    modifyTime: null,
    startDate: null,
    endDate: null,
    timeLimit: { number: "", unit: "" } // 修改: timeLimit: null
  };
  packageProductList.value = [];
  proxy.resetForm("hxq_packageRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加套餐管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getHxq_package(_id).then(response => {
    form.value = response.data;
    packageProductList.value = response.data.packageProductList;
    open.value = true;
    title.value = "修改套餐管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["hxq_packageRef"].validate(valid => {
    if (valid) {
      // 将 form.timeLimit 转换为 JSON 字符串
      form.value.timeLimit = JSON.stringify(form.value.timeLimit);
      form.value.packageProductList = packageProductList.value;
      if (form.value.id != null) {
        updateHxq_package(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addHxq_package(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除套餐管理编号为"' + _ids + '"的数据项？').then(function() {
    return delHxq_package(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** ${subTable.functionName}序号 */
function rowPackageProductIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** ${subTable.functionName}添加按钮操作 */
function handleAddPackageProduct() {
  let obj = {};
  obj.productId = "";
  obj.quantity = "";
  obj.modifyTime = "";
  packageProductList.value.push(obj);
}

/** ${subTable.functionName}删除按钮操作 */
function handleDeletePackageProduct() {
  if (checkedPackageProduct.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的${subTable.functionName}数据");
  } else {
    const packageProducts = packageProductList.value;
    const checkedPackageProducts = checkedPackageProduct.value;
    packageProductList.value = packageProducts.filter(function(item) {
      return checkedPackageProducts.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handlePackageProductSelectionChange(selection) {
  checkedPackageProduct.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('hxq_package/hxq_package/export', {
    ...queryParams.value
  }, `hxq_package_${new Date().getTime()}.xlsx`)
}

// 新增时间限制验证函数
function validateTimeLimit(rule, value, callback) {
  if (!value.number || !value.unit) {
    callback(new Error("时效的数值和单位都不能为空"));
  } else {
    callback();
  }
}
onMounted(() => {
  listProduct().then(response => {
    products.value = response.rows;
  });
});


getList();
</script>
